import { Avatar, Button, Card, Empty, Modal, message } from 'antd'
import './index.scss'
import Meta from 'antd/es/card/Meta'
import { LikeOutlined, DislikeOutlined, MessageOutlined } from '@ant-design/icons'
import BlogComment from './components/BlogComment'
import { useEffect, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { getBlogInfoAPI } from '@/api/blog'
import { getCollectAddAPI, getCollectDeleteAPI } from '@/api/collect'
import { useSelector } from 'react-redux'
import TextArea from 'antd/es/input/TextArea'
import { getReportAddAPI } from '@/api/report'
import dayjs from 'dayjs'

const BlogDetail = () => {

  const location = useLocation()
  const { blogId, isStar, starId } = location.state
  const [star, setStar] = useState(isStar)
  const [starBlogId, setStarBlogId] = useState(starId)

  // 查询博客
  const [blogInfo, setBlogInfo] = useState({})
  const getBlogInfo = async () => {
    const res = await getBlogInfoAPI(blogId)
    setBlogInfo(res.data)
  }
  useEffect(() => {
    getBlogInfo()
  }, [])

  // 获取用户id
  const userId = useSelector(state => state.user.userInfo.id)
  // 处理点赞
  const handleStar = async () => {
    try {
      if (star) {
        const res = await getCollectDeleteAPI(starBlogId)
        if (res.code === 1) {
          message.success('取消点赞成功')
          setStar(false) // 使用函数式更新

        } else {
          message.error(res.msg)
        }
      } else {
        const res = await getCollectAddAPI({ userId, blogId, title: blogInfo.title })
        if (res.code === 1) {
          message.success('点赞成功')
          setStar(true) // 使用函数式更新
          setStarBlogId(res.data)
        } else {
          message.error(res.msg)
        }
      }
      // 重新获取博客信息以更新点赞数量等信息
      getBlogInfo()
    } catch (error) {
      console.error('Error occurred while handling star:', error)
    }
  }

  // 处理举报
  const navigate = useNavigate()
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [textAreaValue, setTextAreaValue] = useState('')
  const showModal = () => {
    setIsModalOpen(true)
  }

  const handleCancel = () => {
    setIsModalOpen(false)
  }
  const handleReport = async () => {
    const res = await getReportAddAPI({blogId, text: textAreaValue})
    if (res.code === 1) {
      setIsModalOpen(false)
      message.success('举报成功')
      navigate(-1)
    } else {
      message.error
    } 
  }


  // 处理评论
  //   抽屉组件
  const [open, setOpen] = useState(false)
  const showDrawer = () => {
    setOpen(true)
  }
  const closeDrawer = (value) => {
    setOpen(value)
  }
  

  return (
    <div className="blog-detail">
      { Object.keys(blogInfo) ?
        <Card className="blog-content-box">
        <div className="content-header">
            <h1 className="title">{blogInfo.title}</h1>
            <Meta
              avatar={<Avatar src="https://api.dicebear.com/7.x/miniavs/svg?seed=8" />}
              title={`作者名：${blogInfo.author}`}
              description={`发布时间：${dayjs(blogInfo.createTime).format('YYYY-MM-DD')}`}
            />
        </div>
        <div className="content-main" dangerouslySetInnerHTML={{ __html: blogInfo.text }}>
        </div>
        <div className="content-footer">
          <Meta
          
            avatar={<Avatar src="https://api.dicebear.com/7.x/miniavs/svg?seed=8" />}
            title={`${blogInfo.author}`}
          />
          <div className="setting">
            <Button 
              size='large' 
              icon={<LikeOutlined/>} 
              style={ star && { color: '#fc5531' }} 
              onClick={handleStar}>
                点赞 
            </Button>
            <Button 
              size='large' 
              icon={<DislikeOutlined/>}
              onClick={showModal}
              >
              举报
            </Button>
            <Modal 
              title="您确定要举报吗？如需举报请填写原因" 
              okText="确认"
              cancelText='取消'
              open={isModalOpen} 
              onOk={handleReport} 
              onCancel={handleCancel}>
              <TextArea value={textAreaValue} onChange={(e) => setTextAreaValue(e.target.value)}></TextArea>
            </Modal>

            <Button 
              size='large' 
              icon={<MessageOutlined />} 
              onClick={showDrawer}>
                评论
            </Button>
          </div>
          <BlogComment 
            open={open} 
            closeDrawer={closeDrawer}
            blogId={blogId}/>
        </div>
      </Card>
      : <div>
      <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
    </div> }
  </div>
  )
}

export default BlogDetail